//
//  NetWorkTool.m
//  LianShangBao
//
//  Created by 主事丫环HU on 2020/8/28.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "NetWorkTool.h"
#import <AFNetworking.h>
#import "NSString+category.h"
//#import "LoginViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "BaseNavViewController.h"
//#import "JPUSHService.h"
@implementation NetWorkTool
+ (void)GET:(NSString *)url param:(id)param success:(void (^)(id dic))success other:(void (^)(id dic))reason fail:(void (^)(NSError *error))fail needUser:(BOOL)need {
    if (![url hasPrefix:@"http://"]) {
        url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    }
    if (need) {
        //if (KUID == nil || [KUID isEqualToString:@""]) {
        //[self clickLogin];
        //return;
        //}
        if (param == nil) {
            param = [NSMutableDictionary dictionary];
        }
        param[@"user_id"] = USER_ID;
//        param[@"token"] = TOKEN;
//        param[@"sign"] = [[USER_ID stringByAppendingString:TOKEN]MD5];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/html", nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"agent"];
    NSString *udid = [USER_DEFAULT objectForKey:@"udid"];
    [manager.requestSerializer setValue:udid forHTTPHeaderField:@"code"];
   
    
    KMyLog(@"_______url______%@", url);
    KMyLog(@"_______param______%@", param);
    
    [manager GET:url parameters:param headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            KMyLog(@"%@",responseObject);
            
            if ([responseObject[@"status"] intValue]==1103) {
                ShowToastWithText(@"登录异常，请重新登录");

                [USER_DEFAULT removeObjectForKey:@"user_id"];
                [USER_DEFAULT synchronize];
     
                return;
            }
            if ([responseObject[@"status"] intValue]==1) {
                success(responseObject);
            } else {
                reason(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            KMyLog(@"%@",error);
            fail(error);
        }];
    
}


+ (void)POST:(NSString *)url param:(id)param success:(void (^)(id dic))success other:(void (^)(id dic))reason fail:(void (^)(NSError *error))fail needUser:(BOOL)need {
    if (![url hasPrefix:@"http://"]) {
        url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/json",@"text/xml", nil];
    [manager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"agent"];
    NSString *udid = [USER_DEFAULT objectForKey:@"udid"];
    [manager.requestSerializer setValue:udid forHTTPHeaderField:@"code"];
    if (param == nil) {
        param = [NSMutableDictionary dictionary];
    }
//    if (need == YES) {
//        [manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
//    }
//    if (need) {
//        if (TOKEN == nil || [TOKEN isEqualToString:@""]) {
//            [self clickLogin];
//            return;
//        }
//        if (param == nil) {
//            param = [NSMutableDictionary dictionary];
//        }
//
//    }
    
    KMyLog(@"_______url______%@", url);
    KMyLog(@"_______param______%@", param);
    [manager POST:url parameters:param headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            KMyLog(@"%@",responseObject);
            
            if ([responseObject[@"status"] intValue]==003) {
                ShowToastWithText(@"登录异常，请重新登录");
                [USER_DEFAULT removeObjectForKey:@"token"];
                [USER_DEFAULT removeObjectForKey:@"user_id"];
                [USER_DEFAULT synchronize];
                [self clickLogin];
                //设置Alias
//                [JPUSHService setAlias:@"" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
//
//                } seq:0];
                return;
            }
            
            if ([responseObject[@"status"] intValue]==004) {
                ShowToastWithText(@"数据异常");
                
    //            [NetWorkTool POST:changeToken param:nil success:^(id dic) {
    //
    //                NSString *toStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"data"]];
    //                [USER_DEFAULT setObject:toStr forKey:@"Token"];
    //
    //                [NetWorkTool POST:url param:param success:^(id dic) {
    //                    success(responseObject);
    //
    //                } other:^(id dic) {
    //                    reason(dic);
    //
    //                } fail:^(NSError *error) {
    //
    //                } needUser:YES];
    //
    //            } other:^(id dic) {
    //
    //            } fail:^(NSError *error) {
    //
    //            } needUser:YES];
            }
            
            if ([responseObject[@"status"] intValue]==1) {
                success(responseObject);
            } else {
                reason(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            KMyLog(@"%@",error);
            if (fail) {
                fail(error);
            }
        }];
}



/**
 添加产品 上传图片
 */
+ (void)apppicUploadPicWithUrl:(NSString *)url param:(NSDictionary *)params key:(NSString *)key image:(id)image withSuccess:(void (^)(id dic))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"agent"];
    NSString *udid = [USER_DEFAULT objectForKey:@"udid"];
    
    [manager.requestSerializer setValue:udid forHTTPHeaderField:@"code"];
    
//    [manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
    //    url = [NSString stringWithFormat:@"%@api/uploader/index.html",HOST_LINK];
    url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    
    KMyLog(@"_______url______%@", url);
    KMyLog(@"_______param______%@", params);
    [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([image isKindOfClass:[UIImage class]]) {
            NSDate *nowDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *imageName = [dateFormatter stringFromDate:nowDate];
            NSString * fileName = [NSString stringWithFormat:@"%@.png",imageName];
            
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data name:key fileName:fileName mimeType:@"image/png"];
        } else {
            for (int i = 0; i<[image count]; i++) {
                
                NSArray *att = image;
                UIImage *image = att[i];
                
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
                // 要解决此问题，
                // 可以在上传时使用当前的系统事件作为文件名
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                // 设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,i];
                
                /*
                 *该方法的参数
                 1. appendPartWithFileData：要上传的照片[二进制流]
                 2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
                 3. fileName：要保存在服务器上的文件名
                 4. mimeType：上传的文件的类型
                 */
                NSString *str = [NSString stringWithFormat:@"upload%d",i];
                if (i  == 0) {
                    [formData appendPartWithFileData:imageData name:@"product_pic" fileName:fileName mimeType:@"image/jpeg"]; //
                } else {
                    [formData appendPartWithFileData:imageData name:str fileName:fileName mimeType:@"image/jpeg"]; //
                }
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        KMyLog(@"%@",responseObject);
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(obj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        KMyLog(@"%@",error);
        failure(error);
    }];
    
}



/**
 上传图片接口
 */
+ (void)UploadPicWithUrl:(NSString *)url param:(NSDictionary *)params key:(NSString *)key image:(id)image withSuccess:(void (^)(id dic))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"agent"];
    NSString *udid = [USER_DEFAULT objectForKey:@"udid"];
    [manager.requestSerializer setValue:udid forHTTPHeaderField:@"code"];
//    [manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
    //url = [NSString stringWithFormat:@"%@api/uploader/index.html",HOST_LINK];
    url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    
    KMyLog(@"_______url______%@", url);
    KMyLog(@"_______param______%@", params);
    [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([image isKindOfClass:[UIImage class]]) {
            NSDate *nowDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *imageName = [dateFormatter stringFromDate:nowDate];
            NSString * fileName = [NSString stringWithFormat:@"%@.png",imageName];
            NSLog(@"%@", fileName);
            
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data name:key fileName:fileName mimeType:@"image/png"];
        } else {
            for (int i = 0; i<[image count]; i++) {
                
                UIImageView *muimagee =image[i];
                UIImage *image = muimagee.image;
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
                // 要解决此问题，
                // 可以在上传时使用当前的系统事件作为文件名
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                // 设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,i];
                NSLog(@"%@", fileName);
                /*
                 *该方法的参数
                 1. appendPartWithFileData：要上传的照片[二进制流]
                 2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
                 3. fileName：要保存在服务器上的文件名
                 4. mimeType：上传的文件的类型
                 */
                NSString *str = [NSString stringWithFormat:@"upload%d",i];
                [formData appendPartWithFileData:imageData name:str fileName:fileName mimeType:@"image/jpeg"]; //
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        KMyLog(@"%@",responseObject);
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(obj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        KMyLog(@"%@",error);
        failure(error);
    }];
    
}



/**
 上传图片接口
 */
+ (void)newUploadPicWithUrl:(NSString *)url param:(NSDictionary *)params key:(NSString *)key image:(id)image withSuccess:(void (^)(id dic))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"agent"];
    NSString *udid = [USER_DEFAULT objectForKey:@"udid"];
    [manager.requestSerializer setValue:udid forHTTPHeaderField:@"code"];
   // [manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
    url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    
    KMyLog(@"_______url______%@", url);
    KMyLog(@"_______param______%@", params);
    [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([image isKindOfClass:[UIImage class]]) {
            NSDate *nowDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *imageName = [dateFormatter stringFromDate:nowDate];
            NSString * fileName = [NSString stringWithFormat:@"%@.png",imageName];
            NSLog(@"%@", fileName);
            
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data name:key fileName:fileName mimeType:@"image/png"];
        } else {
            for (int i = 0; i<[image count]; i++) {
                
                UIImageView *muimagee =image[i];
                UIImage *image = muimagee.image;
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
                // 要解决此问题，
                // 可以在上传时使用当前的系统事件作为文件名
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                // 设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,i];
                NSLog(@"%@", fileName);
                /*
                 *该方法的参数
                 1. appendPartWithFileData：要上传的照片[二进制流]
                 2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
                 3. fileName：要保存在服务器上的文件名
                 4. mimeType：上传的文件的类型
                 */
                NSString *str = [NSString stringWithFormat:@"upload%d",i];
                [formData appendPartWithFileData:imageData name:str fileName:fileName mimeType:@"image/jpeg"]; //
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        KMyLog(@"%@",responseObject);
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(obj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        KMyLog(@"%@",error);
        failure(error);
    }];
    
}



//包含用户签名的POST请求
+ (void)requestLike:(NSMutableDictionary *)param path:(NSString *)path completion:(void (^)(id dic))completion failure:(void (^)(NSError *))failure {
    
    [self POST:path param:param success:^(id dic) {
        completion(dic);
        if ([dic[@"code"] intValue]!=1000) {
            
        }
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        failure(error);
    } needUser:YES];
}



//包含用户签名的GET请求
+ (void)requestGet:(NSMutableDictionary *)param path:(NSString *)path completion:(void (^)(id dic))completion failure:(void (^)(NSError *error))failure {
    if (USER_ID == nil || [USER_ID isEqualToString:@""]) {
        [self clickLogin];
        return;
    }
    if (param == nil) {
        param = [NSMutableDictionary dictionary];
    }
    
    [self GET:path param:param success:^(id dic) {
        completion(dic);
        if ([dic[@"code"] intValue]!=1000) {
            ShowToastWithText(dic[@"msg"]);
        }
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        failure(error);
        
    } needUser:YES];
}



+ (void)clickLogin {
//    LoginViewController *vc = [[LoginViewController alloc]init];
//    BaseNavViewController *nav = [[BaseNavViewController alloc]initWithRootViewController:vc];
//    nav.modalPresentationStyle = UIModalPresentationFullScreen;
//    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
}



//0-普通店铺,1-普通产品,2-同城信息服务,3-资讯收藏,4-商城商家收藏,5-商城产品
+ (void)requestStore:(NSString*)store_id
              column:(NSString*)column_id
                item:(NSString*)item_id
                type:(NSString*)type {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"store_id"] = store_id;
    param[@"column_id"] = column_id;
    param[@"item_id"] = item_id;
    param[@"type"] = type;
    [self requestLike:param path:@"api/favorite/add.html" completion:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } failure:^(NSError *error) {
    }];
}



+ (void)POST:(NSString *)url parameters:(id)parameters progress:(void (^)(id progress))downloadProgress complation:(void (^)(id dic))complaction failure:(void (^)(NSError *error))failure {
    if (![url hasPrefix:@"http://"]) {
        url = [NSString stringWithFormat:@"%@%@",HOST_LINK,url];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
    
    [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (complaction) {
            complaction(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/*else if ([image isKindOfClass:[ALAsset class]]) {
 //视频
 ALAsset *asset = image;
 NSLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url);
 if (asset != nil) {
 NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *docuPath = [documentPaths objectAtIndex:0];
 
 NSString *videoPath= [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.mov",0]];//这里直接强制写一个即可，之前计划是用i++来区分不明视频
 NSURL *url = [NSURL fileURLWithPath:videoPath];
 
 //NSError *theErro = nil;
 //BOOL exportResult = [asset exportDataToURL:url error:&theErro];
 //NSLog(@"exportResult=%@", exportResult?@"YES":@"NO");
 
 NSData *videoData = [NSData dataWithContentsOfURL:url];
 [formData appendPartWithFileData:videoData name:@"file" fileName:@"video1.mov" mimeType:@"video/quicktime"];
 }
 }*/
@end

